<template>
    <div class="system-menu-container">
        <el-dialog title="新增机构" v-model="isShowDialog" width="769px">
            <el-form :model="ruleForm" size="small" label-width="80px">
                <el-row :gutter="35">
                    <el-col :xs="20" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
                        <el-form-item label="用户名">
                            <el-input v-if="has_update" v-model="dtoAioAdmin.adminName" disabled/>
                            <el-input v-if="!has_update"
                                      v-model="dtoAioAdmin.adminName"
                                      @input="onVerifyAdminName($event)"
                                      placeholder="6-16位"
                                      clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="4" :sm="2" :md="2" :lg="2" :xl="2" class="mb20">
                        <i class="el-icon-success" v-show="check.adminName== true"/>
                        <i class="el-icon-error" v-show="!check.adminName == true
                        && dtoAioAdmin.adminName != null
                        && dtoAioAdmin.adminName.length >0"/>
                    </el-col>

                    <el-col :xs="20" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
                        <el-form-item label="密码">
                            <el-input v-model="dtoAioAdmin.adminPass"

                                      @input="onVerifyAdminPass($event)"
                                      type="password"
                                      clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="4" :sm="2" :md="2" :lg="2" :xl="2" class="mb20">
                        <i class="el-icon-success" v-show="check.adminPass== true"/>
                        <i class="el-icon-error" v-show="!check.adminPass == true
                        && dtoAioAdmin.adminPass != null
                        && dtoAioAdmin.adminPass.length >0"/>
                    </el-col>


                    <el-col :xs="20" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
                        <el-form-item label="角色">
                            <el-select v-if="has_update" v-model="value" disabled></el-select>
                            <el-select v-if="!has_update"
                                       v-model="value"
                                       @change="getItem(value,'radio')"
                                       placeholder="选择角色">
                                <el-option v-for="item in options" :key="item.value" :label="item.label"
                                           :value="item.value"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="4" :sm="2" :md="2" :lg="2" :xl="2" class="mb20">
                    </el-col>

                    <el-col :xs="20" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
                        <el-form-item label="姓名">
                            <el-input v-model="dtoAioAdmin.fullName"
                                      @input="onVerifyFullName($event)"
                                      placeholder="2-16位"
                                      clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="4" :sm="2" :md="2" :lg="2" :xl="2" class="mb20">
                        <i class="el-icon-success" v-show="check.fullName== true"/>
                        <i class="el-icon-error" v-show="!check.fullName == true
                        && dtoAioAdmin.fullName != null
                        && dtoAioAdmin.fullName.length >0"/>
                    </el-col>

                    <el-col :xs="20" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
                        <el-form-item label="手机号">
                            <el-input v-model="dtoAioAdmin.phone"
                                      @input="onVerifyPhone($event)"
                                      placeholder="11位手机号"
                                      maxlength="11" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="4" :sm="2" :md="2" :lg="2" :xl="2" class="mb20">
                        <i class="el-icon-success" v-show="check.phone== true"/>
                        <i class="el-icon-error" v-show="!check.phone == true
                        && dtoAioAdmin.phone != null
                        && dtoAioAdmin.phone.length >0"/>
                    </el-col>

                    <el-col :xs="20" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
                        <el-form-item label="机构名称">
                            <el-input v-model="dtoAioAdmin.nickName"
                                      @input="onVerifyNickName($event)"
                                      placeholder="2-16位"
                                      clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="4" :sm="2" :md="2" :lg="2" :xl="2" class="mb20">
                        <i class="el-icon-success" v-show="check.nickName== true"/>
                        <i class="el-icon-error" v-show="!check.nickName == true
                        && dtoAioAdmin.nickName != null
                        && dtoAioAdmin.nickName.length >0"/>
                    </el-col>

                    <el-col :xs="20" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
                        <el-form-item label="推送地址">
                            <el-input v-model="dtoAioAdmin.pushUrl"
                                      placeholder="POST推送"
                                      clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="4" :sm="2" :md="2" :lg="2" :xl="2" class="mb20">
                    </el-col>

                    <el-col :xs="20" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
                        <el-form-item label="头像">
                            <el-upload
                                    class="avatar-uploader"
                                    :action="url"
                                    :headers="head"
                                    name="multipartFile"
                                    :show-file-list="false"
                                    :on-success="handleAvatarSuccess"
                                    :before-upload="beforeAvatarUpload"
                            >
                                <img v-if="dtoAioAdmin.heardUrl" :src="dtoAioAdmin.heardUrl" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>

                        </el-form-item>
                    </el-col>
                    <el-col :xs="4" :sm="2" :md="2" :lg="2" :xl="2" class="mb20">

                    </el-col>

                </el-row>
            </el-form>
            <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="small">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="small">确 定</el-button>
				</span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
	import { addMechAdmin, updMechAdmin } from '/@/api/mech.ts';
	import { getCurrentInstance, reactive, toRefs } from 'vue';
	import { clearSession, getSession } from '/@/utils/storage.ts';
	import {
		verifyPhone,
		verifyLength_2_16,
		verifyLength_6_16,
		verifyPass_6_16,
	} from '/@/utils/toolsValidate.ts';
	import { setBackEndControlRefreshRoutes } from '/@/router';
	import { useRoute } from 'vue-router';

	export default {
		name: 'mech_admin',
		setup() {
			const { proxy } = getCurrentInstance() as any;
			const route = useRoute();

			const state = reactive({
				isShowDialog: false,
				head: {
					token: '' + getSession('token'),
				},

				url: import.meta.env.VITE_API_URL + '/s-file/api/file/uploads',
				options: [
					{
						label: '机构管理员',
						value: 80,
					},
				],

				value: 80,
				has_update: false,
				/**
				 * 参数请参考 `/src/router/index.ts` 中的 `dynamicRoutes` 路由菜单格式（请注意参数类型！）
				 * 受到 `element plus` 类型 `string/number/object` 影响，不可使用 `:value="true"`
				 * 的写法，所以传值到后台时，需要转换成布尔值，否则页面可能出现玄学。
				 * 路由权限标识为数组格式，基本都需要自行转换类型
				 */
				ruleForm: {
					name: '', // 路由名称
					component: '', // 组件地址
					isLink: '', // 是否外链
					menuSort: '', // 菜单排序
					meta: {
						title: '', // 菜单名称
						icon: '', // 菜单图标
						isHide: '', // 是否隐藏
						isKeepAlive: '', // 是否缓存
						isAffix: '', // 是否固定
						isLink: '', // 是否外链，开启外链条件，`1、isLink:true 2、链接地址不为空`
						isIframe: '', // 是否内嵌，开启条件，`1、isIframe:true 2、链接地址不为空`
						auth: '', // 路由权限标识（多个请用逗号隔开），最后转成数组格式
					},

				},
				dtoAioAdmin: {
					adminId: 0,
					adminName: '',
					adminPass: '',
					roleId: '',
					roleName: '',
					fullName: '',
					phone: '',
					nickName: '',
					heardUrl: '',
					pushUrl: '',
				},
				dialogVisible: false,
				check: {
					adminName: false,
					adminPass: false,
					fullName: false,
					phone: false,
					nickName: false,
				},

			});
			// 打开弹窗
			const openDialog = (row?: object) => {
				console.log('====>>openDialog');
				console.log(row);
				state.has_update = false;
				initForm();
				if (row) {

					console.log('==>> copy row dtoAioAdmin');
					state.has_update = true;

					state.dtoAioAdmin.adminId = row.adminId;
					state.dtoAioAdmin.adminName = row.adminName;
					// state.dtoAioAdmin.adminPass = row.adminPass;
					// state.dtoAioAdmin.roleId = '';
					// state.dtoAioAdmin.roleName = '';
					state.dtoAioAdmin.fullName = row.fullName;
					state.dtoAioAdmin.phone = row.phone;
					state.dtoAioAdmin.nickName = row.nickName;
					state.dtoAioAdmin.heardUrl = row.heardUrl;
					state.dtoAioAdmin.pushUrl = row.pushUrl;

					onVerifyAdminName(state.dtoAioAdmin.adminName);
					onVerifyFullName(state.dtoAioAdmin.fullName);
					onVerifyPhone(state.dtoAioAdmin.phone);
					onVerifyNickName(state.dtoAioAdmin.nickName);

				}

				state.isShowDialog = true;
			};
			// 关闭弹窗
			const closeDialog = (row?: object) => {
				console.log(row);
				state.isShowDialog = false;
				proxy.$emit('fuzujian');

			};
			// 是否内嵌下拉改变
			const onSelectIframeChange = () => {
				if (state.ruleForm.meta.isIframe === 'true') {
					state.ruleForm.isLink = 'true';
				} else {
					state.ruleForm.isLink = '';
				}
			};
			// 取消
			const onCancel = () => {
				closeDialog();
				initForm();
			};
			// 表单初始化，方法：`resetFields()` 无法使用
			const initForm = () => {
				console.log('==>>initForm dtoAioAdmin');
				state.dtoAioAdmin.adminId = 0;
				state.dtoAioAdmin.adminName = '';
				state.dtoAioAdmin.adminPass = '';
				state.dtoAioAdmin.roleId = '';
				state.dtoAioAdmin.roleName = '';
				state.dtoAioAdmin.fullName = '';
				state.dtoAioAdmin.phone = '';
				state.dtoAioAdmin.nickName = '';
				state.dtoAioAdmin.heardUrl = '';
			};
			// 提交
			const onSubmit = () => {
				state.dtoAioAdmin.roleId = state.value;
				// console.log(state.dtoAioAdmin); // 数据，请注意需要转换的类型
				if (state.has_update) {
					updMechAdmin(state.dtoAioAdmin).then((res: any) => {
						if (res.code == 1001) {
							closeDialog(); // 关闭弹窗
							// setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
							// parent.location.reload(); //F5
						}

					});
				} else {
					addMechAdmin(state.dtoAioAdmin).then((res: any) => {
						if (res.code == 1001) {
							closeDialog(); // 关闭弹窗
							// setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
							// parent.location.reload(); //F5
						}

					});
				}

			};
			//文件上传
			const handleAvatarSuccess = (res, file) => {
				// console.log('==>>')
				// console.log(res.data.fileUrl)
				// state.dtoAioAdmin.heardUrl = URL.createObjectURL(file.raw);
				state.dtoAioAdmin.heardUrl = res.data.fileUrl;
			};
			const beforeAvatarUpload = (file) => {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					proxy.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					proxy.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			};

			//校验
			const onVerifyAdminName = (val: string) => {
				state.check.adminName = verifyLength_6_16(val);
			};
			const onVerifyAdminPass = (val: string) => {
				state.check.adminPass = verifyPass_6_16(val);
			};

			const onVerifyFullName = (val: string) => {
				state.check.fullName = verifyLength_2_16(val);
			};
			// 手机号码
			const onVerifyPhone = (val: string) => {
				state.check.phone = verifyPhone(val);
			};

			const onVerifyNickName = (val: string) => {
				state.check.nickName = verifyLength_2_16(val);
			};

			const getItem = (obj, type) => {
				console.log(obj);
				console.log(type);
			};
			return {
				openDialog,
				closeDialog,
				onSelectIframeChange,
				onCancel,
				onSubmit,
				...toRefs(state),
				handleAvatarSuccess,
				beforeAvatarUpload,

				onVerifyAdminName,
				onVerifyAdminPass,
				onVerifyFullName,
				onVerifyPhone,
				onVerifyNickName,
				getItem,
			};
		},
	};
</script>

<style>
    .avatar-uploader {
        width: 8rem;
        height: 8rem;


    }

    .avatar {
        width: 8rem;
        height: 8rem;

    }

    .el-icon-success {
        color: #22bc76;
        font-size: 1.5rem;
    }

    .el-icon-error {
        color: red;
        font-size: 1.5rem;
    }
</style>
